<?php
namespace app\api\controller\soft;
use app\providers\BaseController;
use think\Image;
use OSS\OssClient;
use OSS\Core\OssException;
use think\facade\Db;
use hg\apidoc\annotation as Apidoc;

/**
 * @Apidoc\Title("上传管理")
 * @Apidoc\Group("base")
 * @Apidoc\Sort(2)
 */
class Upload extends BaseController 
{
	
	protected $tableName = 'xw_system_upload';  			//表名
   
    /**
    * 上传文件
    *  @Apidoc\Author("weifashi")
	* @Apidoc\Url("/api/soft/upload/upload")
    * @Apidoc\Method("POST")
    * @Apidoc\Param("fkGuid", require=false,default="",desc="文件guid" )
    * @Apidoc\Param("ywName", require=false, default="",desc="业务名称" )
    * @Apidoc\Param("fkType", require=false, default="",desc="业务类型" )
    * @Apidoc\Param("desc", require=false, default="",desc="描述" )
    * @Apidoc\Param("classify_id", require=false, default="",desc="所属系统分类id" )
    */
	public function upload($fkGuid='',$ywName='',$fkType='',$desc='',$classify_id=0){
		$fkGuid = $fkGuid ?: "系统文件";
		$ywName = $ywName ?: "系统文件";
		$fkType = $fkType ?: "系统文件";
		
		$files = request()->file();
		$fileId = 0;
	    foreach($files ?: [] as $file){
			//保存的数据
			$data = [];
			
			//文件信息
			$fileType = $file->getType();
			$fileName = $file->getOriginalName();
			$tmpName = $file->getPathName();
			$fileSize = $file->getSize();
			$fileExt = substr($fileName,strrpos($fileName,'.')+1); 
			
            $config = env('SYSTEM_BASE_CONFIG_FILE');
			if($config["type"] == 'oss'){
		        try {
		        	@error_reporting (E_ALL & ~E_NOTICE & ~E_WARNING);
			     	$keyId = $config['accessKeyId'];
			        $keySecret = $config['accessKeySecret'];
			        $endpoint = $config['endpoint']; 
			        $catalog= $config['catalog'];
			        $auth = new OssClient($keyId,$keySecret,$endpoint);
			        $dst = $catalog.date('ymd').'/'.md5(time()).''.'-'.$fileName;  
		            $result = $auth->uploadFile($config['bucket'],$dst,$tmpName);
					$info = $result['info'];
					$filePath =  $info['url'];
					$data['duration'] = $info['total_time']; //这个获得的便是音频文件的时长
		        } catch (OssException $e) {
		        	return \Api::ReError($e->getMessage());
		        }
			}else{
				$filePath = \think\facade\Filesystem::putFile( 'uploads', $file);
				//如果是图片就压缩
				if(strstr($filePath,".jpg")){
					$filePath2 = root_path().'/runtime/storage/'.$filePath;
					$image = Image::open($filePath2);
					$image->thumb(650, 650)->save($filePath2); 
					$data['width'] = $image->width();
					$data['height'] = $image->height();
				}
				//如果是音频就获取时长
				if(strstr($filePath,".mp3") || strstr($filePath,".mp4")){
					include_once('./extend/lib/getid3/getid3.php');
					$getID3 = new \getID3();
					$thisFileInfo = $getID3->analyze($filePath); //分析文件，$path为音频文件的地址
					$data['duration'] = $thisFileInfo['playtime_seconds']; //这个获得的便是音频文件的时长
				}
			}
			
			$data['file_name']= $fileName;
	    	$data['file_path']=  $filePath;
	    	$data['file_guid']= "$fkGuid";
	    	$data['file_type']= "$fkType";
	    	$data['file_buss_type']= "$ywName";
	    	$data['file_description']="$desc";
	    	$data['type']= $fileType;
	    	$data['size']= $fileSize;
	    	$data['ext']= $fileExt;
	    	$data['classify_id']= $classify_id;
	    	$fileId = Db::table(  $this->tableName )->insertGetId($data);
	    }

		if($fileId){
			if( strstr($data['file_path'],"http://") ||  strstr($data['file_path'],"https://") ){
				$file_path = $data['file_path'];
			}else{
				$file_path = env('APP_HOST').'/'.str_replace("\\","/",$data['file_path']);
			}
			return \Api::ReSucess(["id"=> $fileId,"src"=>$file_path],'上传成功！');
		}else{
			return \Api::ReError('上传失败！');
		}
		
	}

	
    /**
    *  删除附件
    * @Apidoc\Author("weifashi")
	* @Apidoc\Url("/api/soft/upload/deleteFile")
    * @Apidoc\Method("POST")
    * @Apidoc\Param("fileIds", require=true,default="",desc="附件ids" )
    */
	public function deleteFile($fileIds){
		$result = Db::table($this->tableName)->where("file_id","in",$fileIds)->select()->toArray();
		if( empty($result) ){
			return \Api::ReError("文件不存在！");
		}else{
			foreach ($result as $fies){
				//$savepath = str_replace(public_path(),'.',$fies['file_path']);
				@unlink( root_path().'/runtime/storage/'.$fies['file_path']);//删除文件
			}
			Db::table($this->tableName)->where("file_id","in",$fileIds)->delete();
		}
		return \Api::ReSucess($result);
	}
	
	
   	
	
}